import { createRouter, createWebHashHistory } from 'vue-router'
import Index from '@/pages/index.vue'
import Login from '@/pages/login.vue'
import NotFound from '@/pages/404.vue'
import Test from '@/pages/test.vue'
import Admin from '@/layout/admin.vue'
import GoodList from '@/pages/goods/list.vue'
import CategoryList from '@/pages/category/list.vue'

// 通用路由
const routes = [
  {
    path: '/',
    name: 'admin',
    component: Admin,
  },
  {
    path: '/login',
    name: 'login',
    component: Login,
    meta: {
      title: '登录页',
    },
  },
  {
    path: '/test',
    name: 'test',
    component: Test,
    meta: {
      title: '测试页',
    },
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound,
    meta: {
      title: '404页面',
    },
  },
]

// 动态路由
const asyncRoutes = [
  {
    path: '/',
    component: Index,
    meta: {
      title: '后台首页',
    },
  },
  {
    path: '/goods/list',
    component: GoodList,
    meta: {
      title: '商品列表',
    },
  },
  {
    path: '/category/list',
    component: CategoryList,
    meta: {
      title: '分类列表',
    },
  },
]

export const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

// 动态添加路由的方法
export function addRoutes(menus) {
  // 是否有新的路由
  let hasNewRoutes = false
  function findAndAddRoutesByMenus(arr) {
    arr.forEach((e) => {
      let item = asyncRoutes.find((o) => o.path === e.frontpath)
      // 在动态路由中查找出路由，并判断该路由是否之前已经注册过
      if (item && !router.hasRoute(item.path)) {
        router.addRoute('admin', item)
        hasNewRoutes = true
      }

      if (e.child && e.child.length > 0) {
        findAndAddRoutesByMenus(e.child)
      }
    })
  }

  findAndAddRoutesByMenus(menus)
  // console.log(router.getRoutes())
  return hasNewRoutes
}
